package org.springblade.common.utils.validation;

import org.springblade.common.utils.validation.constraints.DatePattern;
import org.springblade.core.tool.utils.Func;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * @Description 日期格式校验
 * @Author ysq
 * @Date 2023/5/25
 **/
public class DatePatternValidator implements ConstraintValidator<DatePattern,String> {

	private DatePattern datePattern;

	@Override
	public void initialize(DatePattern constraintAnnotation) {
		this.datePattern = constraintAnnotation;
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if (Func.isBlank(value)) {
			return true;
		}

		String format = datePattern.format();
		if (value.length() != format.length()) {
			return false;
		}

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		try {
			simpleDateFormat.parse(value);
		}catch (ParseException e) {
			return false;
		}

		return true;
	}

}

